package com.example.tt_bells_v02;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.Toast;

public class ActivityExpandBell extends Activity implements OnClickListener {

	DatePicker			pick_start;
	DatePicker			pick_end;
	
	RadioButton			filter_none;
	RadioButton			filter_weekends_on;
	RadioButton			filter_weekends_off;
	RadioButton			filter_daystep;
	
	Button				button_expand_bell;
	Button				button_set_start_date;
	Button				button_set_end_date;
	
	ServiceConnection 	sconn;
	boolean 			bound = false;
	BellManager			bm = null;
	Bell				exp_bell = null;
		
	int 				call_idx = 999;
	
	Time				date_min = new Time(Time.getCurrentTimezone());
	Time				date_max = new Time(Time.getCurrentTimezone());
	//int					y_min,y_max,m_min,m_max,d_min,d_max; //expansion borders
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_expand_bell);
		
		setTitle("Expand bell to range of dates");
		//TODO: put somewhere info: if day already contains 
		//bell with same name, it won't be duplicated
				
		filter_none = (RadioButton)findViewById(R.id.filter_none);
		filter_weekends_on = (RadioButton)findViewById(R.id.filter_weekends_on);
		filter_weekends_off = (RadioButton)findViewById(R.id.filter_weekends_off);
		filter_daystep = (RadioButton)findViewById(R.id.filter_daystep);
		
		button_expand_bell = (Button)findViewById(R.id.button_expand_bell);
		button_expand_bell.setOnClickListener(this);
		button_set_start_date = (Button)findViewById(R.id.button_set_start_date);
		button_set_end_date = (Button)findViewById(R.id.button_set_end_date);
		
		Intent calling = getIntent();
	    call_idx = (int)calling.getIntExtra("index", -1);
		
		sconn = new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				Log.d(Tag.TAG,"Service disconnected from ActivityExpandBell");
				bm = null;
				bound = false;
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder binder) {
				Log.d(Tag.TAG,"Service connected to ActivityExpandBell");
				bm = ((BellManager.MyBinder)binder).getService();
				bound = true;
				
				if (call_idx >= 0) {
					exp_bell = bm.bellHolder.get(call_idx);
					//pre-set date pickers
					date_min.set(exp_bell.alarm_time);
					if (exp_bell.bell_type == BellInfo.BELL_TYPE_PERIODIC) {
						date_max.set(exp_bell.last_alarm_time.toMillis(true)+60000*60*24);
					} else {
						date_max.set(exp_bell.alarm_time.toMillis(true)+60000*60*24);
					}
					
					button_set_start_date.setText(date_min.format("%Y.%m.%d")+" - click to pick");
					button_set_end_date.setText(date_max.format("%Y.%m.%d")+" - click to pick");
				}
			}
		};
		
		bindService(new Intent(this, BellManager.class), sconn, 0);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	
		if (bound) unbindService(sconn);
	}
	
	public void showDatePickerDialog(View v) {
		//Log.d(Tag.TAG,""+v.getId());
	    DatePickerFragment newFragment = new DatePickerFragment();
	    //newFragment.setCallerId(v.getId());
	    switch (v.getId()) {
	    	case R.id.button_set_start_date: {
	    		newFragment.setData(date_min, button_set_start_date);
	    	break; }
	    	case R.id.button_set_end_date: {
	    		newFragment.setData(date_max, button_set_end_date);
	    	break; }
	    }
	    //newFragment.setData(t, b)
	    newFragment.show(getFragmentManager(), "datePicker");
	}
	
	@Override
	public void onClick(View v) {
		boolean do_expand = false;
		boolean is_second_day = false;
		int selected_filter = 0;
		int expansion_counter = 0;
		
		if (v.getId() != R.id.button_expand_bell) return;
		
		//TODO: filter index const
		if (filter_none.isChecked()) selected_filter = 0;
		if (filter_weekends_off.isChecked()) selected_filter = 1;
		if (filter_weekends_on.isChecked()) selected_filter = 2;
		if (filter_daystep.isChecked()) selected_filter = 3;
		
		if ((v.getId() == R.id.button_expand_bell) && bound) {
			//1) Check date range for correctness
			if (DayCompare.isBefore(date_max,date_min)) {
				Toast.makeText(this, "End day cannot be before start day!", Toast.LENGTH_SHORT).show();
				return;
			}
			if (DayCompare.isSameDay(date_min, exp_bell.alarm_time) &&
				DayCompare.isSameDay(date_max, exp_bell.alarm_time)) {
				Toast.makeText(this, "Your bell already exists in selected day!", Toast.LENGTH_SHORT).show();
				return;
			}
			//2) Prepare 
			Bell newbell;
			Time newtime = new Time(date_min);
			//3) Create-and-add cycle
			while (DayCompare.isBefore(newtime, date_max)) {
				switch (selected_filter) {
					case 3: { //each second day (We can use only one variable, but let it be as is)
						do_expand = is_second_day;
						is_second_day = !is_second_day;
					break; }
					case 2: { //only weekends
						if ((newtime.weekDay == Time.SATURDAY) || (newtime.weekDay == Time.SUNDAY))
							do_expand = true;
						else
							do_expand = false;
					break; }
					case 1: { //only work days
						if ((newtime.weekDay != Time.SATURDAY) && (newtime.weekDay != Time.SUNDAY))
							do_expand = true;
						else
							do_expand = false;
					break; }
					default: { //no filter = filter_none
						do_expand = true;
					break; }
				}
				if (do_expand) {
					expansion_counter++;
					newbell = new Bell(exp_bell);
					newbell.id = bm.debug_id++;
					newbell.setAlarmDay(newtime);
					bm.bellHolder.add(newbell);
				}
				//increment day
				newtime.monthDay++;
				newtime.normalize(true);
			}
		}
		
		//TODO: maybe more detail report in case of error
		if (expansion_counter == 0) {
			Toast.makeText(v.getContext(), "No new bells were created", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(v.getContext(), "Successfully created "+expansion_counter+" new bell(s).", Toast.LENGTH_SHORT).show();
		}
		finish();
	}
	
	public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
	
		int caller_id = 0;
		Button		caller_button = null;
		Time		caller_time = null;
		
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);
			
			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}
		
		public void setCallerId(int id) {
			caller_id = id;
		}
		
		public void setData(Time t, Button b) {
			caller_time = t;
			caller_button = b;
		}
		
		public void onDateSet(DatePicker view, int year, int month, int day) {
			if ((caller_button != null) && (caller_time != null)) {
				caller_time.set(day, month, year);
				caller_button.setText(caller_time.format("%Y.%m.%d")+" - click to pick");
			}
		}
	}
}
